package com.zygh.coordinatestore.util;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.net.InetSocketAddress;

@Data
@Component
public class UdpServer {
    private Bootstrap serverBootstrap;

    private InetSocketAddress udpPort;

    private Logger logger = LoggerFactory.getLogger(UdpServer.class);

    @Resource(name = "bootstrap")
    public void setServerBootstrap(Bootstrap serverBootstrap) {
        this.serverBootstrap = serverBootstrap;
    }

    @Resource(name = "udpSocketAddress")
    public void setTcpPort(InetSocketAddress udpPort) {
        this.udpPort = udpPort;
    }

    private Channel serverChannel;

    public void start()  {
        logger.info("netty 开启");
        try{
            serverChannel =  serverBootstrap.bind(udpPort).sync().channel().closeFuture().sync().channel();
        }catch (Exception e){
            logger.error(e.toString());
        }

    }

    @PreDestroy
    public void stop() {
        logger.info("netty 关闭");
        serverChannel.close();
        serverChannel.parent().close();
    }
}
